import hashlib
from google.appengine.ext import db
import logging
import Cookie
class User(db.Model):
  """This is the model that will hold the user email and password that we will 
  use to do our own auth"""
  salt = db.StringProperty()
  hashed_password = db.StringProperty()
  email = db.StringProperty(required=True)
  
  importantMessages = db.ListProperty(int,required=True,default=None)
  readMessages = db.ListProperty(int,required=True,default=None)
  groups = db.ListProperty(int, default=None)
  firstTime = db.BooleanProperty(required=True,default=True)
  avatar = db.BlobProperty()
  displayname = db.StringProperty()
  aboutMe = db.StringProperty(default="",multiline=True)
  website = db.StringProperty(default="")
  moderator = db.BooleanProperty(default=False)
  super_user = db.BooleanProperty(default=False)
  
  
  # this is the temporary instance variable that  
  password = str()
  
  def put(self):
    """Override the default put method to salt and hash our password before we 
    store it in the db."""
    
    # when the object is first created make sure that we create empty group list
    if self.firstTime:
      self.groups = list()
      self.salt = "1h78f"
      self.hashed_password = hashlib.md5(self.password + self.salt).hexdigest()
    # make sure that every super_user is also a moderator
    if self.super_user:
      self.moderator = True
    
    db.Model.put(self)
    
def authenticate(email=None, password=None):
  """This is a statis method that you can call to do the authentication 
  checking"""
  query = User.all()
  query.filter("email = ", email)
  user = query.get()
  logging.info(user)
  # check if the email is in the db
  if user:
    # query = User.all()
    # query.filter("email = ", email)
    tmp_hash = hashlib.md5(password + user.salt).hexdigest()
    logging.info(tmp_hash)
    logging.info(user.hashed_password)
    # query.filter("hashed_password = ", tmp_hash)
    if user.hashed_password == tmp_hash:
      return user
    else:
      return None
    # res = query.get()
    
    # if the user is in the db then make sure that the password is correct
    # if res:
      # return res
    # else:
      # return None
      
  else:
    return None
    
def get_current_user(request):
  """ method that will return the user who is currently logged in. requires 
  that you pass in the request that is currently being processed. Will return 
  none if there is no user logged in """
  cookie = Cookie.SimpleCookie()
  header = request.headers.get('Cookie')
  if header:
    cookie.load(header)
    
    # get the session id
    session_id = cookie["session_id"].value
    logging.info(session_id)
    
    # check to see if we have a -1 session value which means invalid
    if session_id == "-1":
      logging.info("inside for loop")
      return None
    user_id = cookie['user_id'].value
    user_id = int(user_id)
    return User.get_by_id(user_id)
  